//
//  WaterMeterController.m
//  PropertyMananger
//
//  Created by bh on 17/2/23.
//  Copyright © 2017年 BH. All rights reserved.
//

#import "WaterMeterController.h"
#import "CheckFormCell.h"
#import "CheckComfirmCell.h"
#import "CheckFromInputCell.h"
#import "AddressView.h"
#import "HouseQueryModel.h"
#import "RoomNumberCell.h"
#import "RoomNumController.h"
#import "SelectedMonthView.h"
#import "BilingCycleModel.h"

@interface WaterMeterController ()<SelectedRoomNumDelegate,SelectedMonthViewDelegate>
@property (nonatomic,copy) NSString * adressStr;//选择地址
@property (nonatomic,copy) NSString * roomNumStr;//选择房间号
@property (nonatomic,strong)  NSDateComponents* comp;//系统的时间

@property (nonatomic,strong) NSMutableArray * floorArray;//楼栋数据源
@property (nonatomic,copy) NSString * selectedTime;//选择的的时间


@property (nonatomic,copy) NSString * BuildUnitId;//楼栋ID
@property (nonatomic,copy) NSString * roomNum;//房间号
@property (nonatomic,copy) NSString * readingNum;//抄表读数

@property (nonatomic,strong) SelectedMonthView * selectedView;
@property (nonatomic,copy) NSString * yearStr;
@property (nonatomic,copy) NSString * selectedTimeStr;
@property (nonatomic,assign) NSInteger  selectedMonth;//选择月份

@property (nonatomic,strong) NSMutableArray * billingCycleArr;//计费周期
@property (nonatomic,strong) NSMutableArray * selectedMonthArr;//选择的周期
@property (nonatomic,copy) NSString * billingCycleStr;//计费周期
//@property (nonatomic,copy) NSString * checkTime;//当前的超表日期

@property (nonatomic,strong) BilingCycleModel * model;

@end

@implementation WaterMeterController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.adressStr = @"请选择楼栋";
    self.roomNumStr = @"请选择房间号";
    self.yearStr = @"请选择周期";
    
    
    [self initTableViewWithView:self.view frame:CGRectMake(0, 50, BHscreenW, BHscreenH) isGroup:NO];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = BHGrayColor;
    
    self.floorArray = [[NSMutableArray alloc]init];
    self.billingCycleArr = [[NSMutableArray alloc]init];
    self.selectedMonthArr = [[NSMutableArray alloc]init];
    
    [self getYearAndMonthData];
    
    [self postChargeBillingCycle];

    
}

#pragma mark - TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 5;
    }else{
        return 1;
    }
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            CheckFormCell * cell = [CheckFormCell cellWithTableView:tableView];
            cell.iconImg.image = IMG(@"ico_meter_reading_ban");
            cell.titleLabel.text = @"楼栋";
            cell.subTitle.text = self.adressStr;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
            return cell;
            
        }else if (indexPath.row == 1){
            
            CheckFormCell * cell = [CheckFormCell cellWithTableView:tableView];
            
            cell.titleLabel.text = @"房号";
            cell.iconImg.image = IMG(@"ico_meter_reading_room");
            cell.subTitle.text = self.roomNumStr;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

                    
            return cell;
            
        }else if (indexPath.row == 2){
            
            CheckFromInputCell * cell = [CheckFromInputCell cellWithTableView:tableView];
            cell.iconImg.image = IMG(@"ico_meter_reading_reading");
            cell.titleLabel.text = @"读数";
            cell.inputTF.placeholder = @"请输入抄表读数";
            
            self.readingNum = cell.inputTF.text;
            
            return cell;
            
        }else if (indexPath.row == 3){
            
            CheckFormCell * cell = [CheckFormCell cellWithTableView:tableView];
            cell.titleLabel.text = @"计费周期";
            cell.subTitle.text = self.yearStr;
            cell.iconImg.image = IMG(@"ico_meter_reading_cycle");
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
            
        }else if (indexPath.row == 4){
            
            CheckFormCell * cell = [CheckFormCell cellWithTableView:tableView];
            cell.titleLabel.text = @"抄表日期";
            cell.subTitle.text = self.selectedTime;
            cell.iconImg.image = IMG(@"ico_meter_reading_date");
            
            return cell;
            
        }
        
    }else if (indexPath.section == 1){
        
        CheckComfirmCell * cell = [CheckComfirmCell cellWithTableView:tableView];
        [cell.comfirmBtn addTarget:self action:@selector(queryClick:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        
        return 50;
    }else{
        return 170;
    }
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 15;
    }else{
    
    return 0.001f;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            {
                AddressView *addressView = [[AddressView alloc] initWithFrame:CGRectMake(0, 0, [UIApplication sharedApplication].keyWindow.frame.size.width, [UIApplication sharedApplication].keyWindow.frame.size.height)];
                addressView.block = ^(NSString *addressStr){
                    
                    DLog(@"选择了 === %@",addressStr);
                    self.adressStr = addressStr;
                    
                    [self.tableView reloadData];

                };
                
                addressView.BuildUnitIDBlock = ^(NSString * BuildUnitId){
                
                    DLog(@"BuildUnitId===%@",BuildUnitId);
                    self.BuildUnitId = BuildUnitId;
                };
                
                [addressView showView:self.view];
                
            }
        }else if (indexPath.row == 1){
        
            if ([self.adressStr isEqualToString:@"请选择楼栋"]) {
                
                [MBProgressHUD showError:@"请选择楼栋" time:1.5];
            }else{
            
                DLog(@"选择房间号");
                RoomNumController * roomVC = [[RoomNumController alloc]init];
                roomVC.delegate = self;
                roomVC.BuildUnitId = self.BuildUnitId;
                
                [self.navigationController pushViewController:roomVC animated:NO];
            }
           
        
        }else if (indexPath.row == 3){
            
            self.selectedView = [[SelectedMonthView alloc]initWithFrame:CGRectMake((self.view.frame.size.width - 270)/2, self.view.frame.size.height/2-80, 270, 210)];
            [self.view addSubview:self.selectedView];
            self.selectedView.monthArray = self.selectedMonthArr;
            
            self.selectedView.delegate = self;
            
            [self.selectedView selectedMonthView];
        
        }
    }

}
#pragma mark - 选择周期实现方法
- (void)didSelectMonth:(NSInteger)num{
    NSLog(@"点击了 == %ld",(long)num);
    
    self.selectedMonth = [[NSString stringWithFormat:@"0%ld",num+1]integerValue];
    
    DLog(@"====%ld",self.selectedMonth);

//    if (num <9) {
//        
//        self.yearStr = [NSString stringWithFormat:@"%ld-0%ld",self.comp.year,self.selectedMonth];
//    }else{
//        
//        self.yearStr = [NSString stringWithFormat:@"%ld-%ld",self.comp.year,self.selectedMonth];
//    }
  
    BilingCycleModel * model = self.billingCycleArr[num];
    
    self.yearStr = model.ItemName;
    
    DLog(@"==%@",self.yearStr);
    
    
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSString stringWithFormat:@"%ld",self.selectedMonth] forKey:@"month"];
    [userDefaults synchronize];
    
    
    
    [self.tableView reloadData];
    
  //  [self postSaveReadingData];
    
    
}

#pragma mark - 实现房号选择代理
- (void)didSelectedRoomNum:(NSString *)roomNum{

    DLog(@"%@",roomNum);
    self.roomNumStr = roomNum;

    [self.tableView reloadData];
}
#pragma mark - 点击查询
- (void)queryClick:(UIButton *)button{
    
    DLog(@"点击提交");
    
      CheckFromInputCell * cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
      self.readingNum = cell1.inputTF.text;
    
    //截取系统时间
    NSArray * timeArr = [self.selectedTime componentsSeparatedByString:@"-"];
    NSString * selectedTime = [NSString stringWithFormat:@"%@-%@",timeArr[0],timeArr[1]];
    
    DLog(@"self.selectedTime==%@---self.yearStr==%@",selectedTime,self.yearStr);
   
    if ([self.adressStr isEqualToString:@"请选择楼栋"]) {
        
       [MBProgressHUD showError:@"请选择楼栋" toView:self.view time:1.5];
        
    }else if ([self.roomNumStr isEqualToString:@"请选择房间号"]){
    
     [MBProgressHUD showError:@"请选择房间号" toView:self.view time:1.5];
        
    }else if ([self.readingNum isEqualToString:@""]){
        
        [MBProgressHUD showError:@"请输入读数" toView:self.view time:1.5];
    
    }else if ([self.yearStr isEqualToString:@"请选择周期"]){
        
         [MBProgressHUD showError:@"请选择周期" toView:self.view time:1.5];
        
    }else if (self.yearStr > selectedTime){
    
        [MBProgressHUD showError:@"请选择小于抄表日期的周期" toView:self.view time:1.5];
        
    }else{
    
        [self postSaveReadingData];
    }
    
    
}
- (void)postSaveReadingData{

        NSDictionary * parms = @{
                                 @"Cid":userModel.CommunityID,
                                 @"BuildUnitId":self.BuildUnitId,
                                 @"MeterReadingType":@"1",
                                 @"CurrentMeterReading":self.readingNum,
                                 @"MeterReadingMan":userModel.RealName,
                                 @"RoomName":self.roomNumStr,
                                 @"MeterReadingTime":self.selectedTime,
                                 @"ChargeBillCycle":self.yearStr,
                                 @"json":@"\{\"jsonEntity\":\{},\"action\":\"savereading\",\"version\":\"V1.0\"}"};
    DLog(@"抄表提交的参数===%@",parms);
    
        [HomeNetWorkRequest postSaveReadingQuerySuccess:^(id data) {
    
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
            NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
            NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
           DLog(@"提交抄表查询数据 == %@",dict);
            DLog(@"%@",dict[@"Msg"]);
            for (NSDictionary * dict in array) {
    
                HouseQueryModel * model = [[HouseQueryModel alloc]init];
    
                [model setValuesForKeysWithDictionary:dict];
    
                [self.floorArray addObject:model];
            }
            
            if ([[dict[@"Code"] stringValue] isEqualToString:@"-3"]) {
                
                [MBProgressHUD showError:dict[@"Msg"] toView:self.view time:1.5];
                
            }else if ([[dict[@"Code"] stringValue] isEqualToString:@"1"]){
            
          
                 [MBProgressHUD showError:dict[@"Msg"] toView:self.view time:1.5];
                
//                __block WaterMeterController * weakSelf = self;
//                
//                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
//                
//                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//                    
//                    [weakSelf.navigationController popViewControllerAnimated:YES];
//                });
                
                
            }
    
            [self.tableView reloadData];
            
        } Fail:^(NSString *errorDes) {
            
        } param:parms];
    
}
#pragma mark - 获取计费周期数据
- (void)postChargeBillingCycle{

    NSDictionary * parms = @{
                             @"ItemType":@"ChargeBillCycle",
                             @"json":@"\{\"jsonEntity\":\{},\"action\":\"calculatecycle\",\"version\":\"V1.0\"}"};
    DLog(@"抄表周期的参数===%@",parms);
    
    [HomeNetWorkRequest postChargeBillingCycleSuccess:^(id data) {
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSString * str = [NSString stringWithFormat:@"%@",dict[@"Data"]];
        NSData * data2 = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        DLog(@"抄表周期数据 == %@",array);
       
        DLog(@"%@",dict[@"Msg"]);
        for (NSDictionary * dict in array) {
            
            BilingCycleModel * model = [[BilingCycleModel alloc]init];
            
            [model setValuesForKeysWithDictionary:dict];
            
            [self.billingCycleArr addObject:model];
            [self.selectedMonthArr addObject:[NSString stringWithFormat:@"%@月",model.ItemValue]];
        }
       
        
        [self.selectedView.collectionView reloadData];
        
    } Fail:^(NSString *errorDes) {
        
    } param:parms];
    

}
#pragma mark - 获取系统时间
- (void)getYearAndMonthData{
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSTimeInterval time = [zone secondsFromGMTForDate:date];
    NSDate *dateNow = [date dateByAddingTimeInterval:time];
    NSString * timeDataStr = [NSString stringWithFormat:@"%@",dateNow];
    DLog(@" === %@",dateNow);
    
    NSArray * arr = [timeDataStr componentsSeparatedByString:@" "];
    DLog(@"日期格式化 == %@",arr[0]);
    
    NSArray * timeArr = [timeDataStr componentsSeparatedByString:@"-"];
    NSString * timeStr = [NSString stringWithFormat:@"%@-%@",timeArr[0],timeArr[1]];
    DLog(@"拼接好的时间===%@",timeStr);
    self.selectedTime = arr[0];
    

}

//- (void)getYearData{
//    
//    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//    // 获取当前日期
//    NSDate * dt = [NSDate date];
//    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
//    unsigned unitFlags = NSCalendarUnitYear |
//    NSCalendarUnitMonth |  NSCalendarUnitDay |
//    NSCalendarUnitHour |  NSCalendarUnitMinute |
//    NSCalendarUnitSecond | NSCalendarUnitWeekday;
//    // 获取不同时间字段的信息
//    self.comp = [gregorian components: unitFlags fromDate:dt];
//    
//    self.selectedTimeStr = [NSString stringWithFormat:@"%ld月",self.comp.month];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}


@end
